package obecto.task.conditional
{
	import flash.events.Event;
	
	import obecto.event.EventDescriptor;
	import obecto.list.CheckList;
	import obecto.task.BaseTask;
	import obecto.utility.Listener;

	[DefaultProperty("preconditions")]
	public class PreconditionsTask extends BaseTask
	{
		[ArrayElementType("obecto.event.EventDescriptor")]
		public var preconditions : Array;
		
		private var preconditionsCheckList : CheckList;
		
		override protected function startActual() : void
		{
			preconditionsCheckList = new CheckList();
			for each (var precondition : EventDescriptor in preconditions)
			{
				preconditionsCheckList.addItem(precondition);
				var listener : Listener = Listener.createSingleTimeDataForwardingListener(
					precondition.eventSource, precondition.eventName, 
					handlePreconditionMet, precondition);
			}
		}
		
		protected function handlePreconditionMet(e : Event, precondition : EventDescriptor) : void
		{
			preconditionsCheckList.checkItem(precondition);
			
			if (preconditionsCheckList.isComplete)
			{
				complete();
			}
		} 
		
	}
}